<template>
  <div id="contestDetailView">
    <a-card :bordered="false">
      <template #title>
        <div class="contest-header">
          <h2>{{ contestInfo.title }}</h2>
          <div class="contest-status">
            <a-tag :color="getStatusColor(contestInfo.status)">
              {{ getStatusText(contestInfo.status) }}
            </a-tag>
          </div>
        </div>
      </template>
      <template #extra>
        <a-space>
          <a-button
            v-if="!contestInfo.hasRegistered"
            type="primary"
            @click="showRegisterModal"
          >
            报名参加
          </a-button>
          <a-button
            v-else-if="contestInfo.status === 1"
            type="primary"
            @click="startContest"
          >
            开始竞赛
          </a-button>
        </a-space>
      </template>

      <a-row :gutter="16">
        <a-col :span="16">
          <a-tabs v-model:activeKey="activeTabKey">
            <a-tab-pane key="info" tab="竞赛信息">
              <div class="contest-info">
                <a-descriptions title="基本信息" bordered>
                  <a-descriptions-item label="开始时间">
                    {{ formatDate(contestInfo.startTime) }}
                  </a-descriptions-item>
                  <a-descriptions-item label="竞赛时长">
                    {{ contestInfo.duration }} 分钟
                  </a-descriptions-item>
                  <a-descriptions-item label="竞赛类型">
                    {{ getContestTypeText(contestInfo.contestType) }}
                  </a-descriptions-item>
                  <a-descriptions-item label="罚时">
                    {{ contestInfo.penalty }} 分钟
                  </a-descriptions-item>
                  <a-descriptions-item label="排名可见">
                    {{ contestInfo.visibleRank ? "是" : "否" }}
                  </a-descriptions-item>
                  <a-descriptions-item label="参赛人数">
                    {{ contestInfo.registrationCount || 0 }}
                  </a-descriptions-item>
                </a-descriptions>

                <div class="contest-description">
                  <h3>竞赛描述</h3>
                  <div class="content">{{ contestInfo.description }}</div>
                </div>
              </div>
            </a-tab-pane>
            <a-tab-pane
              key="problems"
              tab="题目列表"
              :disabled="!contestInfo.hasRegistered"
            >
              <a-table
                :columns="problemColumns"
                :data-source="problemList"
                :loading="problemsLoading"
                :pagination="false"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.dataIndex === 'title'">
                    <a @click="viewProblem(record)">{{ record.title }}</a>
                  </template>
                  <template v-if="column.dataIndex === 'acceptedRate'">
                    {{
                      record.submitNum
                        ? (
                            (record.acceptedNum / record.submitNum) *
                            100
                          ).toFixed(1)
                        : "0.0"
                    }}% ({{ record.acceptedNum }}/{{ record.submitNum }})
                  </template>
                </template>
              </a-table>
            </a-tab-pane>
            <a-tab-pane
              key="ranking"
              tab="排名"
              :disabled="!contestInfo.visibleRank"
            >
              <a-table
                :columns="rankingColumns"
                :data-source="rankingList"
                :loading="rankingLoading"
                :pagination="false"
              >
                <template #bodyCell="{ column, record }">
                  <template v-if="column.dataIndex === 'user'">
                    {{ record.userVO?.userName }}
                  </template>
                  <template
                    v-if="column.key && column.key.startsWith('problem_')"
                  >
                    <div
                      v-if="
                        record.questionStatusMap &&
                        record.questionStatusMap[column.problemId]
                      "
                    >
                      <template
                        v-if="record.questionStatusMap[column.problemId].solved"
                      >
                        <a-tag color="green">
                          {{
                            record.questionStatusMap[column.problemId].attempts
                          }}次
                          {{
                            formatTimePenalty(
                              record.questionStatusMap[column.problemId].penalty
                            )
                          }}
                        </a-tag>
                      </template>
                      <template v-else>
                        <a-tag color="red">
                          -{{
                            record.questionStatusMap[column.problemId].attempts
                          }}
                        </a-tag>
                      </template>
                    </div>
                  </template>
                </template>
              </a-table>
            </a-tab-pane>
          </a-tabs>
        </a-col>
        <a-col :span="8">
          <a-card title="倒计时" :bordered="false" class="countdown-card">
            <div v-if="contestInfo.status === 0">
              <h3>距离开始还有</h3>
              <div class="countdown">{{ countdown }}</div>
            </div>
            <div v-else-if="contestInfo.status === 1">
              <h3>距离结束还有</h3>
              <div class="countdown">{{ countdown }}</div>
            </div>
            <div v-else>
              <h3>竞赛已结束</h3>
            </div>
          </a-card>

          <a-card
            title="我的统计"
            :bordered="false"
            class="stats-card"
            v-if="contestInfo.hasRegistered"
          >
            <a-statistic
              title="已解决"
              :value="myStats.solved"
              style="margin-right: 16px"
            />
            <a-statistic
              title="总提交"
              :value="myStats.total"
              style="margin-right: 16px"
            />
            <a-statistic title="排名" :value="myStats.rank" />
          </a-card>
        </a-col>
      </a-row>
    </a-card>

    <!-- 竞赛注册弹窗 -->
    <a-modal
      v-model:visible="registerModalVisible"
      title="竞赛报名"
      @ok="doRegister"
      okText="报名"
      cancelText="取消"
    >
      <a-form
        :model="registerForm"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="竞赛标题" name="title">
          <span>{{ contestInfo.title }}</span>
        </a-form-item>
        <a-form-item label="竞赛时间" name="time">
          <span>{{ formatDate(contestInfo.startTime) }}</span>
        </a-form-item>
        <a-form-item label="竞赛时长" name="duration">
          <span>{{ contestInfo.duration }} 分钟</span>
        </a-form-item>
        <a-form-item
          v-if="contestInfo.contestType === 1"
          label="竞赛密码"
          name="password"
        >
          <a-input-password
            v-model:value="registerForm.password"
            placeholder="请输入竞赛密码"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
/* eslint-disable */
import { onMounted, onUnmounted, ref, reactive, computed, h } from "vue";
import { useRoute, useRouter } from "vue-router";
import { message, Tag as ATag } from "ant-design-vue";
import { ContestControllerService } from "../../../generated/services/ContestControllerService";
import { ContestSubmitControllerService } from "../../../generated/services/ContestSubmitControllerService";
import { useStore } from "vuex";
import { formatDate, formatTimePenalty } from "@/utils/dateUtil";

// 初始化数据
const route = useRoute();
const router = useRouter();
const store = useStore();
const user = store.state.user.loginUser;

// 竞赛ID
const contestId = computed(() => Number(route.params.id));

// 竞赛信息
const contestInfo = ref({
  id: 0,
  title: "",
  description: "",
  contestType: 0,
  startTime: "",
  duration: 0,
  status: 0,
  visibleRank: 1,
  penalty: 0,
  registrationCount: 0,
  hasRegistered: false,
});
const loading = ref(false);
const activeTabKey = ref("info");

// 题目列表
const problemList = ref([]);
const problemsLoading = ref(false);
const problemColumns = [
  {
    title: "题号",
    dataIndex: "id",
  },
  {
    title: "标题",
    dataIndex: "title",
  },
  {
    title: "通过率",
    dataIndex: "acceptedRate",
  },
  {
    title: "难度",
    dataIndex: "difficulty",
    customRender: ({ text }) => {
      if (text === 0) return "简单";
      if (text === 1) return "中等";
      if (text === 2) return "困难";
      return "未知";
    },
  },
];

// 排名列表
const rankingList = ref([]);
const rankingLoading = ref(false);
const rankingColumns = ref([
  {
    title: "排名",
    dataIndex: "rank",
    width: 80,
  },
  {
    title: "用户",
    dataIndex: "user",
    width: 150,
  },
  {
    title: "解题数",
    dataIndex: "solvedCount",
    width: 100,
  },
  {
    title: "罚时",
    dataIndex: "totalPenalty",
    width: 100,
    customRender: ({ text }) => formatTimePenalty(text),
  },
]);

// 我的统计
const myStats = reactive({
  solved: 0,
  total: 0,
  rank: "-",
});

// 注册相关
const registerModalVisible = ref(false);
const registerForm = reactive({
  contestId: undefined,
  password: "",
});

// 倒计时
const countdown = ref("");
let timer = null;

// 获取竞赛信息
const getContestInfo = async () => {
  try {
    loading.value = true;
    const res = await ContestControllerService.getContestByIdUsingGet(
      contestId.value
    );
    if (res.code === 0) {
      contestInfo.value = res.data;
      updateCountdown();

      // 设置定时器更新倒计时
      timer = setInterval(() => {
        updateCountdown();
      }, 1000);

      if (contestInfo.value.hasRegistered) {
        loadProblemList();
        loadMyStats();
      }

      if (contestInfo.value.visibleRank) {
        loadRankingList();
      }
    } else {
      message.error("获取竞赛信息失败");
    }
  } catch (error) {
    console.error("获取竞赛信息异常", error);
    message.error("获取竞赛信息异常");
  } finally {
    loading.value = false;
  }
};

// 更新倒计时
const updateCountdown = () => {
  const now = new Date().getTime();
  let targetTime;

  if (contestInfo.value.status === 0) {
    // 未开始，倒计时到开始时间
    targetTime = new Date(contestInfo.value.startTime).getTime();
  } else if (contestInfo.value.status === 1) {
    // 进行中，倒计时到结束时间
    const startTime = new Date(contestInfo.value.startTime).getTime();
    targetTime = startTime + contestInfo.value.duration * 60 * 1000;
  } else {
    countdown.value = "已结束";
    return;
  }

  const diff = targetTime - now;
  if (diff <= 0) {
    countdown.value = "已结束";
    getContestInfo(); // 重新获取竞赛信息以更新状态
    return;
  }

  // 计算时分秒
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((diff % (1000 * 60)) / 1000);

  if (days > 0) {
    countdown.value = `${days}天 ${hours}小时 ${minutes}分 ${seconds}秒`;
  } else {
    countdown.value = `${hours}小时 ${minutes}分 ${seconds}秒`;
  }
};

// 加载题目列表
const loadProblemList = async () => {
  // 需要后端提供获取竞赛题目的接口
  // 此处假设 contestInfo.questionList 已包含题目列表
  if (contestInfo.value.questionList) {
    problemList.value = contestInfo.value.questionList;
  }
};

// 加载排名
const loadRankingList = async () => {
  try {
    rankingLoading.value = true;
    const res = await ContestControllerService.getContestRankUsingGet(
      contestId.value
    );
    if (res.code === 0) {
      rankingList.value = res.data;

      // 动态生成题目列
      const problemColumns =
        contestInfo.value.questionList?.map((problem, index) => {
          return {
            title: String.fromCharCode(65 + index), // A, B, C...
            key: `problem_${problem.id}`,
            problemId: problem.id,
            width: 80,
            align: "center",
          };
        }) || [];

      rankingColumns.value = [
        {
          title: "排名",
          dataIndex: "rank",
          width: 80,
        },
        {
          title: "用户",
          dataIndex: "user",
          width: 150,
        },
        ...problemColumns,
        {
          title: "解题数",
          dataIndex: "solvedCount",
          width: 100,
          sorter: (a, b) => a.solvedCount - b.solvedCount,
        },
        {
          title: "罚时",
          dataIndex: "totalPenalty",
          width: 100,
          customRender: ({ text }) => formatTimePenalty(text),
          sorter: (a, b) => a.totalPenalty - b.totalPenalty,
        },
      ];
    } else {
      message.error("获取排名失败");
    }
  } catch (error) {
    console.error("获取排名异常", error);
  } finally {
    rankingLoading.value = false;
  }
};

// 加载我的统计
const loadMyStats = async () => {
  try {
    if (!user) return;

    // 获取我的解题数
    const solvedRes =
      await ContestSubmitControllerService.getUserSolvedCountUsingGet(
        contestId.value
      );
    if (solvedRes.code === 0) {
      myStats.solved = solvedRes.data;
    }

    // 获取我的提交记录
    const submitsRes =
      await ContestSubmitControllerService.getUserContestSubmitsUsingGet(
        contestId.value
      );
    if (submitsRes.code === 0) {
      myStats.total = submitsRes.data.length;
    }

    // 找到我的排名
    if (rankingList.value.length > 0) {
      const myRanking = rankingList.value.find(
        (item) => item.userId === user.id
      );
      if (myRanking) {
        myStats.rank = myRanking.rank;
      }
    }
  } catch (error) {
    console.error("获取我的统计异常", error);
  }
};

// 竞赛类型显示
const getContestTypeText = (type) => {
  const typeMap = {
    0: "公开",
    1: "密码保护",
    2: "私有",
  };
  return typeMap[type] || "未知";
};

// 竞赛状态显示
const getStatusText = (status) => {
  const statusMap = {
    0: "未开始",
    1: "进行中",
    2: "已结束",
  };
  return statusMap[status] || "未知";
};

const getStatusColor = (status) => {
  const colorMap = {
    0: "blue",
    1: "green",
    2: "red",
  };
  return colorMap[status] || "default";
};

// 查看题目
const viewProblem = (problem) => {
  router.push(`/contest/${contestId.value}/problem/${problem.id}`);
};

// 显示报名弹窗
const showRegisterModal = () => {
  registerForm.contestId = contestId.value;
  registerForm.password = "";
  registerModalVisible.value = true;
};

// 报名竞赛
const doRegister = async () => {
  try {
    const res = await ContestControllerService.registerContestUsingPost({
      contestId: registerForm.contestId,
      password: registerForm.password,
    });
    if (res.code === 0) {
      message.success("报名成功");
      registerModalVisible.value = false;
      getContestInfo(); // 重新获取竞赛信息
    } else {
      message.error(res.message || "报名失败");
    }
  } catch (error) {
    console.error("报名竞赛异常", error);
    message.error("报名失败");
  }
};

// 开始竞赛
const startContest = async () => {
  try {
    const res = await ContestControllerService.startContestUsingPost(
      contestId.value
    );
    if (res.code === 0) {
      message.success("开始竞赛成功");
      router.push(
        `/contest/${contestId.value}/problem/${
          contestInfo.value.questionList?.[0]?.id || 0
        }`
      );
    } else {
      message.error(res.message || "开始竞赛失败");
    }
  } catch (error) {
    console.error("开始竞赛异常", error);
    message.error("开始竞赛失败");
  }
};

// 生命周期钩子
onMounted(() => {
  getContestInfo();
});

onUnmounted(() => {
  // 清除定时器
  if (timer) {
    clearInterval(timer);
  }
});
</script>

<style scoped>
#contestDetailView {
  padding: 24px;
}

.contest-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.contest-header h2 {
  margin: 0;
}

.contest-description {
  margin-top: 24px;
}

.contest-description h3 {
  margin-bottom: 16px;
}

.contest-description .content {
  white-space: pre-wrap;
}

.countdown-card {
  margin-bottom: 16px;
}

.countdown {
  font-size: 20px;
  font-weight: bold;
  color: #1890ff;
  margin-top: 8px;
}
</style>
